<style lang="less">
	/*@import './international.less';*/
</style>

<template>
	<div>
		<Row :gutter="16">
			<Col>
			<Card>
				<searchbar @onSearch="searchList" ref="searchbar" v-bind="searchbar" @searchbarClear="clear">
					<template>
						<span v-for="input in searchbar.inputs" :key="input.sn">
							<span v-if="!input.type">{{input.text}} <Input v-model='searchbar.queryParams[input.sn]' :style="input.style"></Input></span>
							<span v-if="input.type === 'autoSelect'">{{input.text}} <autoSelect :model.sync="searchbar.queryParams[input.sn]" :url="input.url"
																								:textField="input.textField" :valueField="input.valueField"
																								:style="input.style" :params="input.params"></autoSelect></span>
							<span v-if="input.type === 'select'">{{input.text}}
								<Select v-model="searchbar.queryParams[input.sn]" :style="input.style" :clearable="input.clearable" :multiple="input.multiple">
									<Option v-for="option in input.options" :value="option.value" :key="option.key || option.value">{{option.text}}</Option>
								</Select>
							</span>
							<span v-if="input.type === 'datetime'">{{input.text}}
								<DatePicker ref="datetime" type="datetime" style="width: 200px" :format="input.format"
											@on-change="searchbar.queryParams[input.sn]=$event"></DatePicker>
							</span>
						</span>
					</template>
					<template v-if="searchbar.hideButtons" slot="buttons">
						<span></span>
					</template>
				</searchbar>
			</Card>
			</Col>

			<Col>
			<Card>
				<toolbar v-bind="toolbar" ref="toolbar"></toolbar>
				<br>
				<List ref="list" v-bind="list" @tableOnRowDblclick="tableOnRowDblclick"></List>
			</Card>
			</Col>
		</Row>

		<Modal v-model="show" :title="title" :loading="true" @on-ok="ok" :mask-closable="false" ref="modal">
			<slot name="modal"></slot>
		</Modal>
	</div>
</template>

<script>
    import List from './list.vue';
    import util from '@/libs/util';
    import searchbar from './searchbar.vue';
    import toolbar from '@/views/common/toolbar.vue';
    import Vue from "vue";
    import autoSelect from '@/views/common/autoSelect.vue';
    import _ from 'lodash';

    // 默认界面查询条件
    //	let pageParams = Object.assign({}, util.queryParams, { // 额外的参数,比如条件的默认值
    //
    //    });

    let initDetailData = {};

    export default {
        name: 'common-page',
        components: {
            List,
            searchbar,
            toolbar,
            autoSelect
        },
        props: {
            exportCurrentPageConfiguration: {
                type: Function,
                default(){
                    return () => {

                    };
                }
            },
            handleToolbarButton: {
                type: Function,
                default () {
                    return () => {
                    };
                }
            },
            toolbar: {
                type: Object,
                default: () => ({
                    menuSn: "",
                    buttons: []
                })
            },
            list: {
                type: Object,
                default: () => {
                    return {
                        table: {
                            columns: [],
                            data: []
                        },
                        url: "",
                        queryParams: {}
                    }
                }
            },
            searchbar: {
                type: Object,
                default: () => {
                    return {
                        queryParams: {},
                        inputs: [],
                        hideButtons: false
                    }
                }
            },
            pageParams: {
                type: Object,
                default(){
                    return {};
                }
            },
            detailData: { // slot里的数据
                type: Object,
                default(){
                    return {};
                }
            },
            form: {
                type: Object,
                default(){
                    return null;
                }
            }
        },
        data () {
            return {
                // modal
                show: false,
                title: "信息页面",
                currentButton: {}
            };
        },
        methods: {
            clear (){ // 情况datepicker
                if (this.$refs.datetime && this.$refs.datetime.length) {
                    this.$refs.datetime.forEach((value, index, arr) => {
                        value.currentValue = undefined;
                    });
                }
            },
            searchList(){ // 查询list数据
                this.$refs.list.load();
            },
            initToolbar(){ // 初始化toolbar
                let me = this;
                util.post({
                    url: "page/list",
                    params: {
                        menuSn: this.toolbar.menuSn,
                        sortName: "sort",
                        sortOrder: "asc",
                        state: "1"
                    },
                    ajaxSuccess(response){
                        let data = response.data;
                        let buttons = data.data.total === undefined ? data.data : data.data.list;
                        let toolbar = buttons.filter((value) => {
                            return value.type === "toolbar";
                        });
                        toolbar.forEach((value) => {
                            value.click = (value) => { //
                                me.buttonClick({
                                    button: value
                                });
                            }
                        });
                        me.toolbar.buttons = toolbar;

                        let rowbar = buttons.filter((value) => {
                            return value.type === "rowbar";
                        });
                        rowbar.forEach((value) => {
                            value.click = (value) => { //
                                me.buttonClick({
                                    button: value
                                });
                            }
                        });
                        me.list.table.columns.push({
                            title: '操作', key: 'action',
                            render: (h, params) => {
                                let rowbuttons = rowbar.map((value) => {
                                    let a = h('Button', {
                                        props: {
                                            type: me.$refs.toolbar.buttonType(value),
                                            size: 'small'
                                        },
                                        on: {
                                            click(){
                                                me.buttonClick({
                                                    button: value,
                                                    params: params
                                                });
                                            }
                                        }
                                    }, value.text);
                                    return a;
                                });
                                return h('div', rowbuttons);
                            }
                        });

                    }
                });
            },
            buttonClick(cnf){ // 按钮点击
                let me = this;
                let button = cnf.button;
                let params = cnf.params;
                if (util.oneOf(button.sn, ["add", "edit", "detail"])) {
                    util.copyProps(this.detailData, initDetailData);
                    if (button.sn === "add") {
                    } else if (util.oneOf(button.sn, ["edit", "detail"])) {
                        this.ajaxLoad(cnf);
                    } else if (button.sn === "detail") {

                    }
                    this.title = button.text + "页面";
                    this.show = true;
                    this.currentButton = button;
                } else if (button.sn === "delete") {
                    let ids = [];
                    let arr = me.$refs.list.$refs.table.getSelection();
                    arr.forEach((value) => {
                        ids.push(value.id);
                    });
                    if (!ids.length) {
                        Vue.prototype.$Message.error({
                            content: "请选择至少一行数据",
                            duration: 4,
                            closable: true
                        });
                        return;
                    }
                    this.$Modal.confirm({
                        content: "确定删除" + ids.length + "条数据?",
                        onOk(){
                            me.ajaxSubmit({
                                buttonType: me.currentButton.sn,
                                url: me.toolbar.menuSn + "/delete",
                                data: ids
                            });
                        }
                    });
                } else if (button.sn === "exportCurrentPage") { // 导出当前页
                    let table = me.$refs.list.$refs.table;
                    let exportCurrentPageConfiguration = _.cloneDeep(me.exportCurrentPageConfiguration({
							commonPage: me
						})) || {
                            filename: "数据.csv"
                        };
                    table.exportCsv(exportCurrentPageConfiguration);
                } else {
                    me.handleToolbarButton(cnf);
                }
            },
            ok () {
                let me = this;
                if (util.oneOf(this.currentButton.sn, ["add", "edit"])) {
                    if (me.form) { // 如果传了form提交的时候就需要校验这个form,否则就直接提交
                        me.form.validate((valid) => {
                            if (!valid) {
                                me.$refs.modal.buttonLoading = false;
                                me.$Message.error({
                                    content: "表单校验失败",
                                    duration: 5,
                                    closable: true
                                });
                            } else {
                                this.ajaxSubmit({
                                    buttonType: this.currentButton.sn,
                                    url: me.toolbar.menuSn + "/save",
                                    data: me.detailData
                                });
                            }
                        })
                    } else {
                        this.ajaxSubmit({
                            buttonType: this.currentButton.sn,
                            url: me.toolbar.menuSn + "/save",
                            data: me.detailData
                        });
                    }
                } else if (me.currentButton.sn == "detail") {
                    me.show = false;
                } else {
                    this.$emit('on-ok');
                }
            },
            ajaxSubmit(cnf){ // 确定提交
                this.$emit("beforeAjaxSubmit");
                let buttonType = cnf.buttonType;
                let url = cnf.url;
                let data = cnf.data;
                var me = this;
                util.post({
                    url: url,
                    params: {},
                    data: data,
                    ajaxSuccess(res){
                        me.show = false;
                        me.$refs.list.load();
                        util.commonAjaxSuccess(res);
                    },
                    ajaxFail(){
                        me.show = false;
                    }
                });
            },
            ajaxLoad(cnf){ // 加载一条数据
                let params = cnf.params;
                let me = this;
                util.post({
                    url: me.toolbar.menuSn + "/load",
                    params: {
                        id: params.row.id
                    },
                    ajaxSuccess(response){
                        let context = response.data;
                        let dto = context.data;
                        util.copyProps(me.detailData, dto);
                        me.emitAjaxLoadSuccess({
                            response: response
                        });
                    }
                });
            },
            getInitDetailData(){
                return initDetailData;
            },
            emitAjaxLoadSuccess(cnf){ // load数据成功时候
                this.$emit("ajaxLoadSuccess", cnf);
            },
            tableOnRowDblclick(obj, index) {
                this.$emit("tableOnRowDblclick", obj, index);
            }
        },
        created () {
        },
        mounted() {
            this.initToolbar(); // 初始化toolbar 按钮
            initDetailData = Object.assign({}, this.detailData); // 拷贝数据
        }
    };
</script>
